package com.wangzhixuan.apiController;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.wangzhixuan.commons.base.ApiBaseController;
import com.wangzhixuan.commons.constant.ApiCode;
import com.wangzhixuan.commons.constant.Constants;
import com.wangzhixuan.commons.easemob.Entry;
import com.wangzhixuan.commons.easemob.model.TalkNode;
import com.wangzhixuan.commons.easemob.service.TalkDataService;
import com.wangzhixuan.commons.jiguang.PushUtils;
import com.wangzhixuan.commons.scan.MyException;
import com.wangzhixuan.commons.utils.StringUtils;
import com.wangzhixuan.commons.utils.date.DateStyle;
import com.wangzhixuan.commons.utils.date.DateUtil;
import com.wangzhixuan.model.BaseInfo;
import com.wangzhixuan.model.Category;
import com.wangzhixuan.model.PeopleWork;
import com.wangzhixuan.model.Rank;
import com.wangzhixuan.model.User;
import com.wangzhixuan.model.vo.BaseInfoVo;
import com.wangzhixuan.model.vo.DescribeVo;
import com.wangzhixuan.model.vo.OpearteVo;
import com.wangzhixuan.model.vo.ReasonVo;
import com.wangzhixuan.model.vo.ResultVo;
import com.wangzhixuan.model.vo.SignVo;
import com.wangzhixuan.model.vo.SurveyBaseVo;
import com.wangzhixuan.service.IAnalysisService;
import com.wangzhixuan.service.IBaseInfoService;
import com.wangzhixuan.service.IDescribeService;
import com.wangzhixuan.service.IPeopleSignService;
import com.wangzhixuan.service.IPeopleWorkService;
import com.wangzhixuan.service.IRankService;
import com.wangzhixuan.service.ISurveyBaseService;
import com.wangzhixuan.service.IUserService;
import com.wangzhixuan.service.impl.AnalysisServiceImpl;
import com.wangzhixuan.service.impl.PeopleWorkServiceImpl;
import com.wangzhixuan.service.impl.UserServiceImpl;

/**
 * <p>
 *   前端控制器
 * </p>
 * @author zhixuan.wang
 * @since 2017-07-19
 */
@Controller
@RequestMapping("/api")
public class BaseInfoApiController extends ApiBaseController {
	
	private final static Logger log= Logger.getLogger(BaseInfoApiController.class);
    
    @Autowired private IBaseInfoService baseInfoService;
    
    @Autowired private ISurveyBaseService surveyBaseService;
    
    @Autowired private IPeopleSignService peopleSignService;
    
    @Autowired private IAnalysisService analysisService;
    
    @Autowired private IDescribeService describeService;
    
    @Autowired private IRankService rankService;
    
    @Autowired private IUserService userService;
    
    @Autowired private IPeopleWorkService peopleWorkService;
    
    
    /**
     * 隐藏图标
     * @param baseInfoVo
     * @return
     * @throws MyException 
     */
    @RequestMapping("function/display")
    @ResponseBody
    public Object display() throws MyException {
    	HashMap<String,Object> map = new HashMap<String,Object>();
    	String[] Array = {"1", "2", "3","4","5","6","7","8"};
    	map.put("display", "YES");
    	map.put("Array", Array);
    	return renderSuccess(ApiCode.CODE_200, "成功",map);
    } 
    
    
    /**
     * 布置工作
     * @param baseInfoVo
     * @return
     * @throws MyException 
     */
    @RequestMapping("/work/add")
    @ResponseBody
    public Object add(BaseInfoVo baseInfoVo) throws MyException {
    	baseInfoVo.checekParam();
    	boolean b = baseInfoService.insertBaseInfo(baseInfoVo);
        if (b) {
        	Integer id = baseInfoService.selectAllBaseInfo(baseInfoVo);
    		PeopleWork peopleWork = new PeopleWork();
    		System.out.println(baseInfoVo.getResponsibleArr());
    		String[] array = baseInfoVo.getResponsibleArr().split(",");
    		System.out.println(array.length);
    		for(int i=0;i<array.length;i++){
    			Integer userId = Integer.valueOf(array[i]);
    			peopleWork.setUserId(userId);
    			peopleWork.setWorkId(id);
    			peopleWork.setCreatTime(new Date());
    			peopleWorkService.insert(peopleWork);
    		}
    		BaseInfo baseInfo = baseInfoService.selectById(id);
    		List<Integer> users = peopleWorkService.selectUser(id);
    		for(int i=0;i<users.size();i++){
            	User selectUserById = userService.selectById(users.get(i));
            	String phone = selectUserById.getPhone();
        		PushUtils.sendPush(phone,"与您相关的"+baseInfo.getJobCategory()+"的"
        		+baseInfo.getJobName()+"工作布置完成",id.toString());					//推送结束
    		}
        	return renderSuccess(ApiCode.CODE_200, "成功");
    	}else{
    		return renderError(ApiCode.CODE_500, "添加失败");
    	}
    }
    
    /**
     * 工作列表
     * 查询状态（1.全部，3.结束）限制给当月（范围）的数据
	 * 查询状态（2.处理中）给全部的数据
     * 
     * @param userId
     * @param statusQuery
     * @param personnelQuery
     * @return
     * @throws MyException 
     * @throws ParseException 
     */
    @RequestMapping("/work/list")
    @ResponseBody
    public Object listCategory(Integer userId,String statusQuery,String personnelQuery,String date) throws MyException, ParseException {
    	if (userId==null) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
        }
		if (StringUtils.isBlank(statusQuery)) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
		if (StringUtils.isBlank(personnelQuery)) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	List<Map<String,Object>> retList = baseInfoService.selectList(userId,statusQuery,personnelQuery,date);	
        return renderSuccess(ApiCode.CODE_200, "成功",retList);
    }
    
    /**
     * 工作详细
     * @param workId
     * @return
     * @throws Exception 
     */
    @RequestMapping("/work/detailed")
    @ResponseBody
    public Object detailed(Integer workId,Integer userId) throws Exception {
    	if (workId==null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	if (userId==null) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
        }
    	Map<String,Object> map = baseInfoService.selectWorkDetail(workId,userId);
    	System.out.println(map);
        return renderSuccess(ApiCode.CODE_200, "成功",map);
    }
    
    /**
     * 提交现场勘察
     * @param baseInfoVo
     * @return
     * @throws NoSuchMethodException 
     * @throws InvocationTargetException 
     * @throws IllegalAccessException 
     */
    @RequestMapping("/survey/add")
    @ResponseBody
    public Object survey(SurveyBaseVo surveyBaseVo) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
    	surveyBaseVo.setCreateTime(new Date());
    	Integer id = surveyBaseService.selectSurveyByWordId(surveyBaseVo.getWorkId());
    	if(id!=null){
    		return renderError(ApiCode.CODE_500, "勘察已完成,请退出重试");
    	}
    	boolean b = surveyBaseService.insertSurveyBaseInfo(surveyBaseVo);
        if (b) {
        	return renderSuccess(ApiCode.CODE_200, "成功");
        } else {
        	return renderError(ApiCode.CODE_500, "添加失败");
        }
    }
    
    @RequestMapping("/survey/detailed")
    @ResponseBody
    public Object surveyDetailed(Integer workId) throws MyException {
/*    	List<Integer> users = peopleWorkService.selectUser(workId);
		for(int i=0;i<users.size();i++){
			Meeting meeting2 = meetingService.selectMeetingByUW(users.get(i).toString(),workId.toString());
			if(meeting2!=null){
				return renderSuccess(ApiCode.CODE_200, "会议已经创建");
			}
		}*/
    	if (workId==null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	Map<String,Object> map = surveyBaseService.selectSurveyDetail(workId);	
        return renderSuccess(ApiCode.CODE_200, "成功",map);
    }
    
    /**
     * 签到
     * @param signVo
     * @return
     * @throws IllegalAccessException
     * @throws InvocationTargetException
     * @throws NoSuchMethodException
     * @throws MyException
     */
    @RequestMapping("/sign/add")
    @ResponseBody
    public Object signAdd(SignVo signVo) throws MyException {
    	signVo.checekParam();
    	Map<String,Object> paramMap = new HashMap<String,Object>();
		paramMap.put("workId", signVo.getWorkId());
		paramMap.put("userId", signVo.getUserId());
		paramMap.put("curDate", DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD));
		String signName = peopleSignService.selectCurDateSign(paramMap);
		if(signName!=null){
			throw new MyException(ApiCode.CODE_1403, "今日已签到，不用重复签到");
		}
    	boolean b = peopleSignService.insertPeopleSign(signVo);
        if (b) {
        	return renderSuccess(ApiCode.CODE_200, "成功");
        } else {
        	return renderError(ApiCode.CODE_500, "添加失败");
        }
    }
    
    /**
     * 获取签到信息
     * @param userId
     * @param workId
     * @return
     * @throws MyException
     */
    @RequestMapping("/sign/detailed")
    @ResponseBody
    public Object signDetailed(Integer userId,Integer workId) throws MyException {
    	if (workId==null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	if (userId==null) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
        }
    	Map<String,Object> map = peopleSignService.selectSignDetail(userId,workId);	
        return renderSuccess(ApiCode.CODE_200, "成功",map);
    }
    
    /**
     * 提交工作问题原因
     * @param reasonVo
     * @return
     * @throws MyException
     */
    @RequestMapping("/work/submitRon")
    @ResponseBody
    public Object submitRon(ReasonVo reasonVo) throws MyException {
    	reasonVo.checekParam();
    	boolean b = analysisService.insertReasons(reasonVo);
        if (b) {
        	return renderSuccess(ApiCode.CODE_200, "成功");
        } else {
        	return renderError(ApiCode.CODE_500, "失败");
        }
    }
    
    @RequestMapping("/workRon/operation")
    @ResponseBody
    public Object operation(OpearteVo opearteVo) throws MyException {
    	opearteVo.checekParam();
    	boolean b = analysisService.updateOpearte(opearteVo);
        if (b) {
        	return renderSuccess(ApiCode.CODE_200, "成功");
        } else {
        	return renderError(ApiCode.CODE_500, "添加失败");
        }
    }
    
    /**
     * 发布人审核工作
     * @param userId
     * @param workId
     * @param workAuditStatus
     * @return
     * @throws Exception 
     */
    @RequestMapping("/work/audit")
    @ResponseBody
    public Object workAudit(Integer userId, Integer workId,Integer workAuditStatus,HttpServletRequest request) throws Exception {
    	if (workId==null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	if (userId==null) {
			throw new MyException(ApiCode.CODE_501, "请重新登录");
        }
    	if (workAuditStatus==null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	BaseInfo baseInfo = baseInfoService.selectById(workId);
    	if(baseInfo==null){
    		throw new MyException(ApiCode.CODE_1402, "此任务不存在");
    	}
    	if(baseInfo.getCreateId()!=userId){
    		throw new MyException(ApiCode.CODE_505, "没有权限操作");
    	}
    	String rootPath = getRootPath();
    	String getbaseUrl = getbaseUrl(request);
    	if(workAuditStatus==2){
    		baseInfo.setStatus(Constants.WORK_STATUS.STATUS6);
    		baseInfo.setInfactEndtime(new Date());							//创建实际结结束时间
    		baseInfoService.updateById(baseInfo);							//执行更新job_base_info
			BaseInfo baseInfo2 = baseInfo.selectById(workId);				//通过查询工作来获取实际于预计结束时间
			Date endTime = baseInfo2.getEndTime();
			Date infactEndtime = baseInfo2.getInfactEndtime();
			int compareTo = endTime.compareTo(infactEndtime);			//预计>=实际(按时完成)返回 0,1 ,否则返回-1
			
			List<Integer> users = peopleWorkService.selectUser(workId);
			for(int k=0;k<users.size();k++){
	    		Rank selectRanking = rankService.selectRanking(users.get(k), workId);  //查询是否有排名
				if(selectRanking==null){									//没有排名执行添加
	    			if(compareTo==0||compareTo==1){
	    				rankService.insertUserOnTime(users.get(k));
	    			}else{
	    				rankService.insertUserDeTime(users.get(k));
	    			}
	    		}else{														
	    			if(compareTo==0||compareTo==1){                                  //有排名执行更新
	    				rankService.updateUserOnTime(users.get(k));
	    			}else{
	    				rankService.updateUserDeTime(users.get(k));
	    			}
	    		}
			}
    	}else{
    		baseInfo.setStatus(Constants.WORK_STATUS.STATUS7);
    		baseInfo.setInfactEndtime(new Date());					//创建实际结束时间
    		baseInfoService.updateById(baseInfo);					//执行更新job_base_info
    		List<Integer> users = peopleWorkService.selectUser(workId);
    		for(int k=0;k<users.size();k++){
	    		Rank selectRanking = rankService.selectRanking(users.get(k), workId);
	    		if(selectRanking==null){
        			Rank rank = new Rank();
        			rank.setDelaytimeNum(0);
        			rank.setFailNum(1);
        			rank.setSucceedNum(0);
        			rank.setTotalOnTimeNum(0);
        			rank.setUserId(users.get(k));
        			rankService.insert(rank);
	    		}else{
		    		rankService.updateUserFail(users.get(k));
	    		}
    		}
    	}
    	String wordUrl = baseInfoService.selectWord(workId,rootPath,getbaseUrl);   			//导出WORD
    	TalkDataService service = Entry.getInstance().getTalkApi();
    	BaseInfo baseInfo2 = baseInfoService.selectById(workId);
    	baseInfo2.setWordUrl(wordUrl);
    	baseInfoService.updateById(baseInfo2);
    	service.groupDrop(baseInfo2.getGroupId());											//解散群聊
        return renderSuccess(ApiCode.CODE_200, "成功");
    }
    
    @RequestMapping("/describe/add")
    @ResponseBody
    public Object describeAdd(DescribeVo describeVo) throws MyException {
    	describeVo.checekParam();
    	describeService.insertDescribe(describeVo);
        return renderSuccess(ApiCode.CODE_200, "成功");
    }
    
    @RequestMapping("/describe/list")
    @ResponseBody
    public Object describeList(Integer workId) throws MyException {
    	if (workId==null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	List<Map<String,Object>> list = describeService.selectDescribeList(workId);	
        return renderSuccess(ApiCode.CODE_200, "成功",list);
    }
    
    @RequestMapping("/work/history")
    @ResponseBody
    public Object history() throws MyException {
    	List<Map<String,Object>> list = baseInfoService.selectAddressList();
        return renderSuccess(ApiCode.CODE_200, "成功",list);
    }
    
    /**
     * 开始工作
     * @param baseInfoVo
     * @return
     * @throws MyException 
     */
    @RequestMapping("/workflow/start")
    @ResponseBody
    public Object start(Integer userId,Integer workId) throws MyException {
    	BaseInfo selectById = baseInfoService.selectById(workId);
    	if(selectById==null){
    		return renderSuccess(ApiCode.CODE_500, "任务不存在");
    	}
    	else{
    		User user = userService.selectById(userId);
    		if(user==null){
    			return renderSuccess(ApiCode.CODE_500, "用户不存在");	
    		}
    		else{
        		BaseInfo baseInfo = baseInfoService.selectById(workId);
        		List<Integer> users = peopleWorkService.selectUser(workId);
        		for(int i=0;i<users.size();i++){
                	User selectUserById = userService.selectById(users.get(i));
                	String phone = selectUserById.getPhone();
            		PushUtils.sendPush(phone,"与您相关的"+baseInfo.getJobCategory()+"的"
            		+baseInfo.getJobName()+"工作布置完成",workId.toString());					//推送结束
        		}
    			BaseInfo selectById2 = baseInfoService.selectById(workId);
    			selectById2.setStatus("5");	 									//代替班后会议的5
    			baseInfoService.updateById(selectById2);
    			return renderSuccess(ApiCode.CODE_200, "成功");
    		}
    	}
    }
    
    
    @RequestMapping("/work/Testing")
    @ResponseBody
    public Object Testing(Integer workId) throws MyException {
    	if (workId==null) {
			throw new MyException(ApiCode.CODE_501, "网络异常，请稍后重试");
        }
    	BaseInfo baseInfo = baseInfoService.selectById(workId);
    	if(baseInfo==null){
    		return renderSuccess(ApiCode.CODE_500, "任务不存在");
    	}
        return renderSuccess(ApiCode.CODE_200, "成功");
    }

}
